const app = getApp();

// 工具栏
import utils from '../../utils/util.js';

// 阳历日期转为农历日期
var date2Lunar = require('../../utils/date2Lunar.js');

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    colorType: {
      // 组件颜色, dark为暗色系, light为浅色系
      type: String,
      value: 'dark'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    lunarTime: '',
    solarDate: '',
    lunarDate: '',
    shouldBe: '',
    notShouldBe: ''
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached: function () {
    /**
     * 初始化农历模块数据
     */
    this.initTime()
    this.initDate()
    const date = utils.formatTime().split(' ')[0]
    if(date === wx.getStorageSync('moon|lunar').date) {
      this.setLunarData(wx.getStorageSync('moon|lunar').res)
    } else {
      this.getChineseAlmanac()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initTime() {
      let _this = this
      let lunarTime = utils.time2Lunar()
      _this.setData({
        lunarTime
      })
      setInterval(function() {
        let lunarTime = utils.time2Lunar()
        _this.setData({
          lunarTime
        })
      }, 10 * 1000)
    },
    initDate() {
      let date = new Date()
      let solarDate = ('0' + (date.getMonth() + 1)).slice(-2) + '月' + ('0' + (date.getDate())).slice(-2) + "日"
      let lunarObj = date2Lunar.sloarToLunar(date.getFullYear(), date.getMonth() + 1, date.getDate())
      let lunarDate = lunarObj.lunarMonth + lunarObj.lunarDay
      this.setData({
        solarDate,
        lunarDate
      })
    },
    getChineseAlmanac() {
      let _this = this
      let date = new Date()
      let today = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + (date.getDate())).slice(-2)
      let key = '98912830a4aa64d32e4bcd460f59592d'
      let url = 'http://v.juhe.cn/laohuangli/d?date=' + today + '&key=' + key
      app._get(url, {},
        (res) => {
          // success callback
          let data = {
            date: res.result.yangli,
            res: res.result
          }
          wx.setStorageSync('moon|lunar', data)
          _this.setLunarData(res.result)
        }, (err) => {
          // error callback
        }, (com) => {
          // complete callback
        })
    },
    setLunarData(e) {
      let shouldBe = ''
      let notShouldBe = ''
      let yiArr = e.yi.split(' ')
      let jiArr = e.ji.split(' ')
      if(yiArr.length >= 2) {
        shouldBe = yiArr[0] + yiArr[1]
      } else {
        shouldBe = yiArr[0]
      }
      if(jiArr.length >= 2) {
        notShouldBe = jiArr[0] + jiArr[1]
      } else {
        notShouldBe = jiArr[0]
      }
      this.setData({
        shouldBe,
        notShouldBe,
      })
    },
    checkLunarDetails() {
      wx.navigateTo({
        url: '/lunarCalendarPack/pages/lunarCalendar/index',
      })
    },
  }
})
